package com.aglie.service.impl;



import cn.hutool.core.io.FileUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.aglie.service.HelloService;
import com.aglie.utils.FileUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class HelloServiceImpl implements HelloService {


    @Override
    public void downloadTemplate(HttpServletResponse response) {

        ExcelWriter writer = ExcelUtil.getWriter();

        String fileName = "指标导入模版.xlsx";

        try {
            ArrayList<String> header = new ArrayList<>();
            header.add("客户代码");

            // 写入第一行的注意事项
            writer.writeCellValue(0, 0, "客户代码");

            // 遍历1到12的月份
            for (int month = 1; month <= 12; month++) {
                // 创建日期对象
                LocalDate date = LocalDate.of(LocalDate.now().getYear(), month, 1);
                // 格式化日期为yyyyMM格式
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMM");
                String yearMonth = date.format(formatter);
                header.add(yearMonth);
            }

            writer.writeRow(header, true);

            // 设置响应头信息
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
//            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString()));
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));

            // 将Excel写入到输出流中
            writer.flush(response.getOutputStream(), true);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            writer.close();
        }


    }

    @Override
    public void templateFormat(MultipartFile file, HttpServletResponse response) throws IOException {
        String filePath = FileUtils.getFilePath(file);
        String fileName = "指标数据导入" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd(HH时mm分ss秒)")) + ".xlsx";
        ServletOutputStream out = response.getOutputStream();

        // 创建ExcelWriter对象
        ExcelWriter writer = ExcelUtil.getWriter(true);
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString()));

        // 写入标题行
        writer.writeRow(Arrays.asList("zddm", "nd", "jhyj"), false);
        ExcelReader reader = ExcelUtil.getReader(filePath);

        ArrayList<String> timeList = new ArrayList<>();
        int currentYear = LocalDate.now().getYear();
        for (int month = 1; month <= 12; month++) {
            LocalDate date = LocalDate.of(currentYear, month, 1);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMM");
            String yearMonth = date.format(formatter);
            timeList.add(yearMonth);
        }

        List<List<Object>> read = reader.read(0);
        read.remove(0);
        for (List<Object> rowList : read) {
            String khdm = rowList.get(0).toString();
            for (int i = 0; i < timeList.size(); i++) {
                ArrayList<Object> rowData = new ArrayList<>();
                rowData.add(khdm);
                rowData.add(timeList.get(i));

                Object yjObj = rowList.get(i + 1);
                String yj = yjObj == null || yjObj.equals("") ? "0" : yjObj.toString();
                if (!yj.equals("")) {
                    BigDecimal number = new BigDecimal(yj);
                    BigDecimal multiplier = new BigDecimal("10000");
                    yj = number.multiply(multiplier).setScale(0, RoundingMode.DOWN).toPlainString(); // 转换为整数格式
                }
                rowData.add(Integer.parseInt(yj)); // 将数据作为 BigDecimal 添加，以便写入为数字格式
                writer.writeRow(rowData, false);
            }
        }

        reader.close();
        writer.flush(out);
        writer.close();
        FileUtil.del(filePath);
    }

}
